import Layout from '@/layout';
import {
  constantRoutes,
  exampleRoutes
} from '@/router';
// import store from '@/store';
/**
 * Use meta.role to determine if the current user has permission
 * @param menus
 * @param route
 */
function hasPermission(menus, route) {
  if (route.meta && route.meta.menus) {
    return menus.some(menus => route.meta.menus.includes(menus))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param menus
 */
export function filterAsyncRoutes(routes, menus) {
  const res = []
  routes.forEach(route => {
    const tmp = {
      ...route
    }
    if (hasPermission(menus, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, menus)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}
const actions = {
  generateRoutes({
    commit
  }, menus) {
    return new Promise(resolve => {
      var routerList = menus;
      let routes = checkRouter(routerList)
      if (process.env.NODE_ENV === 'development') {
        routes = routes.concat(exampleRoutes);
        commit('SET_ROUTES', routes);
      } else {
        commit('SET_ROUTES', routes);
      }
      resolve(routes);
    })
  }
}

function checkRouter(list) {
  var out = [];
  list.forEach(item => {
    var newisCache = false;
    if (item.isCache === 1) {
      newisCache = true
    } else {
      newisCache = false
    }
    var obj = {
      path: item.path,
      hidden: item.hidden,
      component: item.component == 'Layout' ? Layout : () => Promise.resolve(require(`@/views/${item.component}`).default),
      isShow: item.isShow, // 默认保留根目录  false 保留子目录
      meta: {
        title: item.title,
        id: item.id,
        icon: item.icon,
        noCache: !newisCache,
        // name: item.name,
        buttonList: item.buttons // 按钮权限
      }
    }
    item.code && (obj.name = item.code); // item.code 缓存标识
    if (item.children) {
      if (item.children.length) {
        obj.redirect = item.redirect;
        obj.meta.id = item.id;
        obj.children = checkRouter(item.children);
      }
    }
    if (obj.hidden) {
      console.log(obj);
    }
    out.push(obj)
  })
  out.push({
    path: '*',
    redirect: '/404',
    hidden: true
  });
  return out;
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
